﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CapstoneProjectAEReader.Business.Others;
using CapstoneProjectAEReader.Entities.Models;
using CapstoneProjectAEReader.DataAccess.DBAccess;
using CapstoneProjectAEReader.Common.Utility;
using System.Linq;
using System.IO;
using Microsoft.Win32;


namespace CapstoneProjectAEReader.GUIs.LibraryGUI
{
    /// <summary>
    /// Interaction logic for BookInformation.xaml
    /// </summary>
    public partial class BookInformation : UserControl
    {

        #region Attributes

        private DAO _dao;
        private Ebook _ebook;

        private Dictionary<string, string> _dllDic = new Dictionary<string, string>();
        private const string EbookExist = "ebookExisted";
        private const string ImagePath = "Image/Rating/";
        private const string ImageExtension = "_Star.png";
        private const string EbookTitle = "ebook";
        private const string Author = "author";
        private const string Type = "type";
        private const string ImportDate = "date";
        private const string Group = "group";
        private const string Rating = "rating";
        private const string Description = "description";
        private const string Save = "saveButton";
        private const string Cancel = "cancelButton";
        private const string Publisher = "publisher";
        private const string EbookInfo = "ebookInfo";
        private const string Browser = "browser";
        private const string InvalidDate = "invalidDateTime";
        private const string AddGroup = "addGroup";
        private Dictionary<int,string> _ratingImgs = new Dictionary<int, string>
                                                         {
                                                             {0,"/Image/Rating/0_Star.png"},
                                                             {1,"/Image/Rating/1_Star.png"},
                                                             {2,"/Image/Rating/2_Star.png"},
                                                             {3,"/Image/Rating/3_Star.png"},
                                                             {4,"/Image/Rating/4_Star.png"},
                                                             {5,"/Image/Rating/5_Star.png"}
                                                         };
        private Point _getMousePosition;
        private double _getWidthPerStar;
        private int _currentRate = 0;
        private int _databaseRate = 0;
        private BitmapImage _bi3;
        private LocalLibrary _parent;
        private Business.E_book_Reader.IBook _iBook;

        #endregion

        public BookInformation(DTO dto, Ebook ebook,LocalLibrary parent)
        {
            InitializeComponent();
            _dllDic =
                   Utilities.LoadXml(Utilities.GetCurrentLocation() + Constants.CommonCharacters.SlashString +
                                     Constants.StorageStructure.MappingXmlFile);
            _parent = parent;
            _dao =new DAO(dto);
            _ebook = ebook;
            ReloadFormLanguage();
            RebindData();
            btBrowser.Visibility = Visibility.Hidden;
        }

        public BookInformation(DTO dto, LocalLibrary parent)
        {
            InitializeComponent();
            _dllDic =
                   Utilities.LoadXml(Utilities.GetCurrentLocation() + Constants.CommonCharacters.SlashString +
                                     Constants.StorageStructure.MappingXmlFile);
            _dao = new DAO(dto);
            ReloadFormLanguage();
            _parent = parent;
        }

        public void ReloadFormLanguage()
        {
            lbEbookTitle.Content = ResourceReader.GetResourceContent(EbookTitle) + Constants.CommonCharacters.HaiCham;
            lbAuthor.Content = ResourceReader.GetResourceContent(Author) + Constants.CommonCharacters.HaiCham;
            lbType.Content = ResourceReader.GetResourceContent(Type) + Constants.CommonCharacters.HaiCham;
            lbImportDate.Content = ResourceReader.GetResourceContent(ImportDate) + Constants.CommonCharacters.HaiCham;
            lbGroup.Content = ResourceReader.GetResourceContent(Group) + Constants.CommonCharacters.HaiCham;
            lbRating.Content = ResourceReader.GetResourceContent(Rating) + Constants.CommonCharacters.HaiCham;
            lbDescription.Content = ResourceReader.GetResourceContent(Description) + Constants.CommonCharacters.HaiCham;
            lbSave.Content = ResourceReader.GetResourceContent(Save);
            lbCancel.Content = ResourceReader.GetResourceContent(Cancel);
            //lbAddGroup.Content = ResourceReader.GetResourceContent(AddGroup);
            lbBrowser.Content = ResourceReader.GetResourceContent(Browser);
            lbImportPublisher.Content = ResourceReader.GetResourceContent(Publisher);
            gbEbookDetail.Header = ResourceReader.GetResourceContent(EbookInfo);
        }

        public void RebindData()
        {
            txtEbookTitle.Text = _ebook.Title;
            txtAuthor.Text = _ebook.Author;
            FlowDocument tempDoc = new FlowDocument();
            tempDoc.Blocks.Add(new Paragraph(new Run(_ebook.Description)));
            txtDescription.Document = tempDoc;
            lbGroupDt.Text = _ebook.GroupInText;
            lbImportDateDt.Content = _ebook.ImportDate;
            txtPublisher.Content = _ebook.Publisher;
            lbTypeDt.Text = _ebook.Type;
            _bi3 = new BitmapImage();
            _bi3.BeginInit();
            string getURIfromDataBase = _ratingImgs[_ebook.Rating]; 
            string convertURI = getURIfromDataBase.Substring(1);
            _bi3.UriSource = new Uri(convertURI, UriKind.RelativeOrAbsolute);
            _bi3.EndInit();
            imgRating.Height = 24;
            imgRating.HorizontalAlignment = HorizontalAlignment.Center;
            imgRating.Source = _bi3;
            //Get Cover 
            string strTempFolder = Constants.StorageStructure.TempFolder;
            string imageFilePath = strTempFolder + Constants.CommonCharacters.SlashString + _ebook.Title + ".png";
            string getCoverURI = "Image/NoBookCover.png";
            if (File.Exists(imageFilePath))
            {
                _bi3 = null;
                _bi3 = new BitmapImage();
                _bi3.BeginInit();
                //getCoverURI = "pack://application:,,,/CapstoneProjectAEReader;component/bin/Debug/" + imageFilePath;
                getCoverURI = System.IO.Path.GetFullPath(imageFilePath);
                _bi3.UriSource = new Uri(getCoverURI, UriKind.RelativeOrAbsolute);
                _bi3.EndInit();
                imgCover.Source = _bi3;
            } else
            {
                _bi3 = null;
                _bi3 = new BitmapImage();
                _bi3.BeginInit();
                _bi3.UriSource = new Uri(getCoverURI, UriKind.RelativeOrAbsolute);
                _bi3.EndInit();
                imgCover.Source = _bi3;
            }
        }

        private void HandleBtSave(object sender, RoutedEventArgs e)
        {
            var textRange = new TextRange(txtDescription.Document.ContentStart, txtDescription.Document.ContentEnd);
            _ebook.Description = textRange.Text;
            _ebook.Publisher = txtPublisher.Content.ToString();
            if(_ebook.Group.Count == 0)
            {
                _ebook.Group.Add(Constants.UnGroup);
                _ebook.GroupInText = String.Join(Constants.CommonCharacters.Comma, _ebook.Group);
            }
            DateTime temp = new DateTime();
            if(DateTime.TryParse(lbImportDateDt.Content.ToString(), out temp))
            {
                _ebook.ImportDate = temp.ToString(Constants.FullDateTimeFormatToSecond);
                if (!_dao.CheckEbookExist(_ebook))
                {
                    string oldPath = _ebook.Path;
                    string oldBookmarkPath = _ebook.BookmarkPath;
                    _ebook.Path = Utilities.GetCurrentLocation() + Constants.CommonCharacters.SlashString + Constants.StorageStructure.EbookFolder + Constants.CommonCharacters.SlashString +
                               System.IO.Path.GetFileName(_ebook.Path);
                    _ebook.BookmarkPath = Utilities.GetCurrentLocation() + Constants.CommonCharacters.SlashString +
                                          Constants.StorageStructure.EbookFolder + Constants.CommonCharacters.SlashString +
                                          _ebook.Title + Constants.XmlExtension;
                    _dao.InsertEbook(_ebook);
                    Utilities.CopyFile(oldPath,_ebook.Path);
                    Utilities.CopyFile(oldBookmarkPath,_ebook.BookmarkPath);
                }
                else
                {
                    _dao.UpdateEbook(_ebook);
                }
                _parent.RebindGroupData();
                _parent.RebindBookListData(_parent.GetCheckedItem());
                if (null != btCancel.Command)
                {
                    btCancel.Command.Execute(null);
                }        
            }
            else
            {
                Utilities.ShowWarningMesbox(ResourceReader.GetResourceContent(InvalidDate));
            }
            
        }

        private void HandleBtAddGroup(object sender, RoutedEventArgs e)
        {
            GroupList tempGroupList = new GroupList(_dao.Dto.EbookGroup,_dao.Dto,_ebook.Group);
            tempGroupList.ShowDialog();
            if( tempGroupList.DialogResult == true)
            {
                List<EbookGroup> selectedItems = tempGroupList.SelectedItems;
                _ebook.Group = (from i in selectedItems
                               select i.Groupname).ToList();
                _ebook.GroupInText = Utilities.ReturnGroupInText(_ebook.Group);
                RebindData();
            }
            tempGroupList.Close();
        }

        private void selectStarRating(object sender, MouseEventArgs e)
        {
            _getWidthPerStar = Math.Floor(imgRating.ActualWidth * 0.2);
            _getMousePosition = Mouse.GetPosition(imgRating);
            double getXNumber = Math.Round(_getMousePosition.X);
            int getRate = Convert.ToInt32(Math.Round(getXNumber / _getWidthPerStar));
            if (getRate != _currentRate) {
                _bi3 = new BitmapImage();
                _bi3.BeginInit();
                _bi3.UriSource = new Uri(ImagePath + getRate + ImageExtension, UriKind.Relative);
                _bi3.EndInit();
                imgRating.Height = 24;
                imgRating.HorizontalAlignment = HorizontalAlignment.Center;
                imgRating.Source = _bi3;
                _currentRate = getRate;
            }
        }

        private void choseStarRating(object sender, MouseButtonEventArgs e)
        {
            _databaseRate = _currentRate;
        }

        private void checkStarRating(object sender, MouseEventArgs e)
        {
            if (_currentRate != _databaseRate) {
                _bi3 = new BitmapImage();
                _bi3.BeginInit();
                _bi3.UriSource = new Uri(ImagePath + _databaseRate + ImageExtension, UriKind.Relative);
                _bi3.EndInit();
                imgRating.Height = 24;
                imgRating.HorizontalAlignment = HorizontalAlignment.Center;
                imgRating.Source = _bi3;
                _currentRate = _databaseRate;
            }
        }

        private void HandleBtBrowser(object sender, RoutedEventArgs e)
        {
            OpenFileDialog myOpenFileDg = new OpenFileDialog();
            myOpenFileDg.Filter = Constants.FileFilter.PdfEpub;
            if (myOpenFileDg.ShowDialog() == true)
            {
                Ebook ebook = new Ebook();
                string fileExtension = System.IO.Path.GetExtension(myOpenFileDg.FileName);
                object readerObj = null;
                string dllPath = Utilities.GetCurrentLocation() + Constants.CommonCharacters.SlashString +
                                     _dllDic[fileExtension];
                Type[] dllTypes = Assembly.LoadFrom(dllPath).GetTypes();
                string ebookType = fileExtension.Split(Constants.CommonCharacters.Dot)[1];
                foreach (var dllType in dllTypes)
                {
                    if (dllType.Name.Contains(ebookType))
                    {
                        readerObj = Utilities.GetReadingController(dllType, new object[] { myOpenFileDg.FileName });
                        
                    }
                }
                _iBook = (Business.E_book_Reader.IBook)readerObj;
                _ebook = _iBook.GenerateEbookObj(myOpenFileDg.FileName);
                if (_dao.CheckEbookExist(ebook))
                {
                    Utilities.ShowWarningMesbox(ResourceReader.GetResourceContent(EbookExist));
                }
                else
                {
                    _ebook = ebook;
                    RebindData();
                }
            }
        }
    }
}
